import json,random,os,string,copy

class modData():
    #定义一个mod列表
    storage=[]
    storagedict={}

        
    def getKey(self,length=5,keys=[]):
        if type(keys)==dict:
            keys=list(x for x in keys)
        def randomid():
            res=''
            for i in range(0,length):
                res += random.choice(string.ascii_letters+string.digits)
            return res
        result = randomid()
        while result in keys:
            result = randomid()    
        # print(result)
        return result
    def getUuid(self,length=10,ids=[]):
        if type(ids)==dict:
            ids=list(x for x in ids)
        def randomid():
            res=''
            for i in range(0,length):
                res += random.choice("0123456789")
            return int(res)            
        result = randomid()
        while result in ids:
            result = randomid()    
        # print(result)
        return result




    #给定mod路径，读取现有鬼谷八荒的mod数据，并根据结构写入storage
    def __init__(self,path="C:\data\mod_0509",gamePath='C:\Program Files (x86)\Steam\steamapps\common\鬼谷八荒'):
        # print(path)
        self.jsonpath=gamePath+"\\Mod\modFQA\配置修改教程\配置（只读）Json格式"
        dirs = os.listdir(path)
        for modName in dirs:
            modpath = os.path.join(path,modName)
            modinfo_file = os.path.join(modpath,"ModProject\ModProject.cache")
            with open(modinfo_file,mode="r",encoding="utf-8") as m:
                obj = json.loads(m.read())
            obj['path']=modpath   
            self.storage.append(obj)
            self.storagedict[obj['soleID']]=obj

    def read_dramaDialogue(self):
        self.LocalText=self.get_currentObj("LocalText")
        self.dramaDialogue=self.get_currentObj("dramaDialogue")
        self.DramaOptions=self.get_currentObj("DramaOptions")
        self.GameItemCost=self.get_currentObj("GameItemCost")
        
        self.GameItemCost = {self.GameItemCost[x]['costID']:self.GameItemCost[x] for x in self.GameItemCost}

        self.dramaDialogue_mod=self.data['dramaDialogue']['items']
        self.LocalTextKey=[]

        for d in self.dramaDialogue_mod:
            did=d['id']['value']
            self.dramaDialogue[did] =d
            textid = d['dialogue']['id']['value']
            self.LocalText[textid]=d['dialogue']
            self.LocalTextKey.append(d['dialogue']['key']['value'])
            self.LocalTextKey.append(d['title']['key']['value'])

    def modDeepRead(self,data):
        if type(data)==dict:
            for i in data:                
                if i =='condition'and data[i]!={'groupName': [], 'items': []}:
                    res=data[i]['items']
                    self.conditions.extend(res)
                if i =='function' and data[i]!={'groupName': [], 'items': []}:
                    self.functions.extend(data[i]['items'])
                if i =='openFunction' and data[i]!={'groupName': [], 'items': []}:
                    self.functions.extend(data[i]['items'])
                child = data[i]
                if type(child)==dict:
                    self.modDeepRead(child)
                else:
                    if child in ["",[],{}]:
                        continue  
                    if type(child)==int:
                        continue  
                    if type(child)==string:
                        continue   
                    if type(child)==list:
                        for t in child:
                            if type(t)==dict:
                                self.modDeepRead(t)
        if type(data) == list:
            for i in data:
                self.modDeepRead(i)
    
    def modRead(self,path):
        modDataPath = os.path.join(path,"ModProject\ModData.cache")
        modData={}
        with open(modDataPath,mode='r',encoding='utf-8') as md:
            modData=json.loads(md.read())
            md.close()
        self.data=modData        
        print('读取ModData.cache文件完成')
        self.read_dramaDialogue()        
        print('加载剧情及相关文本完成')  

        self.conditions = []
        self.functions = []
        self.reward=[]
        self.rewardChild=[]
        self.modDeepRead(self.data)
        self.rewardCountFunction = list(filter(lambda x:x['key']=={'value': 'rewardCount'},self.functions))

        for i in self.rewardCountFunction:
            if i['values'][0]['value']!="":
                res = json.loads(i['values'][0]['value'])
                self.modDeepRead(res)
                self.reward.append(res)
                for c in res['items']:
                    self.rewardChild.append(c)

        self.conditions={x['id']['value']:x for x in self.conditions}
        self.functions={x['id']['value']:x for x in self.functions}

        #这两个id我还没跟base里面查重
        self.rewardChild={x['id']['value']:x for x in self.rewardChild}
        self.reward={x['rewardID']['value']:x for x in self.reward}
        

        print("深度分析MOD完成")

        return modData

    def modSave(self,path,modData):
        modDataPath = os.path.join(path,"ModProject\ModData.cache")
        with open(modDataPath,mode='w',encoding='utf-8') as md:
            md.write(json.dumps(modData,ensure_ascii=False))
            md.close()

    def functionMake(self,tag=""):
        obj={
            "key": {
                "value": "addAttr"
            },
            "values": [
                {
                    "value": "healthMax"
                },
                {
                    "value": "0"
                },
                {
                    "value": "2"
                },
                {
                    "value": ""
                },
                {
                    "value": ""
                },
                {
                    "value": ""
                },
                {
                    "value": ""
                },
                {
                    "value": ""
                }
            ],
            "modDesc": {
                "value": "1"
            },
            "id": {
                "value": self.getUuid(9,self.functions)
            },
            "tagClassName": {
                "value": tag
            },
            "tagDiscard": {
                "value": 0
            }
        }
        func_id=obj['id']['value']
        self.functions[func_id]=obj
        return obj

    def dialogueMake(self,tag=""):
        obj={
                "uiType": {
                    "value": "1"
                },
                "condition": {
                    "groupName": [],
                    "items": []
                },
                "weight": {
                    "value": 1
                },
                "dialogue": {
                    "key": {
                        "value": self.getKey(5,self.LocalTextKey)
                    },
                    "text": {
                        "value": ""
                    },
                    "id": {
                        "value": self.getUuid(8,self.LocalText)
                    }
                },
                "soundsBg": {
                    "value": "0"
                },
                "soundsEffect": {
                    "value": "0"
                },
                "openFunction": {
                    "groupName": [],
                    "items": []
                },
                "function": {
                    "groupName": [],
                    "items": [  ]
                },
                "dramaOptions": {
                    "groupName": [],
                    "items": []
                },
                "npcLeftType": {
                    "value": "1"
                },
                "npcLeft": {
                    "value": "-1"
                },
                "npcRightType": {
                    "value": "1"
                },
                "npcRight": {
                    "value": "-1"
                },
                "speaker": {
                    "value": "1"
                },
                "title": {
                    "key": {
                        "value": self.getKey(5,self.LocalTextKey)
                    },
                    "text": {
                        "value": ""
                    },
                    "id": {
                        "value": self.getUuid(8,self.LocalText)
                    }
                },
                "backgroud": {
                    "value": ""
                },
                "nextDialogue": {
                    "value": "0"
                },
                "resetLeftNPC": {
                    "value": "0"
                },
                "resetRightNPC": {
                    "value": "0"
                },
                "modDesc": {
                    "value": ""
                },
                "id": {
                    "value": self.getUuid(9,self.dramaDialogue)
                },
                "tagClassName": {
                    "value": tag
                },
                "tagDiscard": {
                    "value": 0
                }
            }
        
        
        did=obj['id']['value']
        self.dramaDialogue[did] =obj
        self.LocalText[obj['dialogue']['id']['value']]=obj['dialogue']
        self.LocalText[obj['title']['id']['value']]=obj['title']
        self.LocalTextKey.append(obj['dialogue']['key']['value'])
        self.LocalTextKey.append(obj['title']['key']['value'])
        return obj

    def get_currentObj(self,obj_name):
        filepath = f"{self.jsonpath}\{obj_name}.json"
        with open(filepath,mode='r',encoding='utf-8') as r:
            res = json.loads(r.read())
            res = {int(x['id']):x for x in res}
            r.close()
        return res





    def reward_fix(self,r):
        #每个产出的物品也要单独处理，既有id，也可能有条件id
        r['id']['value']=self.getUuid(8,self.rewardChild)
        if r['condition']!={'groupName': [], 'items': []}:
            for c in r['condition']['items']:
                c['id']['value']=self.getUuid(8,self.conditions)         
        return r



    def fun_fix(self,f):
        f['id']['value']=self.getUuid(8,self.functions)
        if f['key']['value']=='rewardCount':
            rw = json.loads(f['values'][0]['value'])
            rw['rewardID']['value']=self.getUuid(8,self.reward)
            for r in rw['items']:
                r=self.reward_fix(r)      
            f['values'][0]['value'] = json.dumps(rw,ensure_ascii=False)
        return f




    def function_fix(self,obj_new):
        #需要挨个给function重置ID
        for f in obj_new['function']['items']:
            f=self.fun_fix(f)
        return obj_new

    def option_fix(self,obj_new):
        obj_new['id']['value']=self.getUuid(9,self.DramaOptions)
        if obj_new['condition']!={'groupName': [], 'items': []}:
            for f in obj_new['condition']['items']:f['id']['value']=self.getUuid(8,self.conditions)
        if obj_new['function']!={'groupName': [], 'items': []}:
            for f in obj_new['function']['items']:self.fun_fix(f)  
        # if obj_new['costItem']!={'value': ''}
        obj_new['costItem']['id']['value']=self.getUuid(9,self.GameItemCost)

        return obj_new


    # def reset

    def modCopy(self,obj,objName):
        obj_new=copy.deepcopy(obj)
        if objName=="dramaDialogue":
            obj_new['id']['value']=self.getUuid(9,self.dramaDialogue)
            obj_new['title']['id']['value']=self.getUuid(8,self.LocalText)
            obj_new['title']['key']['value']=self.getKey(5,self.LocalTextKey)
            obj_new['dialogue']['key']['value']=self.getKey(5,self.LocalTextKey)
            obj_new['dialogue']['id']['value']=self.getUuid(8,self.LocalText)
            if obj_new['condition']!={'groupName': [], 'items': []}:
                #需要挨个给condition重置ID
                for f in obj_new['condition']['items']:f['id']['value']=self.getUuid(8,self.conditions)                    
            if obj_new['function']!={'groupName': [], 'items': []}:
                for f in obj_new['function']['items']:self.fun_fix(f)
                # #需要挨个给function重置ID
                # self.function_fix(obj_new)
            if obj_new['openFunction']!={'groupName': [], 'items': []}:
                #需要挨个给openFunction重置ID
                self.function_fix(obj_new)
            did=obj_new['id']['value']
            self.dramaDialogue[did] =obj_new                
            self.LocalText[obj_new['dialogue']['id']['value']]=obj_new['dialogue']
            self.LocalText[obj_new['title']['id']['value']]=obj_new['title']
            self.LocalTextKey.append(obj_new['dialogue']['key']['value'])
            self.LocalTextKey.append(obj_new['title']['key']['value'])            
            return obj_new

        if objName in ["function","openFunction"]:
            obj_new=self.fun_fix(obj_new)
            return obj_new

        if objName=='reward':
            #目前也只有产出物品需要解析json
            obj_new=self.reward_fix(obj_new)
            return obj_new
    

        if objName=="dramaOptions":
            obj_new=self.option_fix(obj_new)
            return obj_new


        return obj_new
